package com.controller;

/**
 * Created by wlc on 2018/4/14.
 */

import com.dao.ExperimentDao;
import com.entity.UserMetadata;
import com.service.ExperimentOperator;
import com.util.CookieUtil;
import com.util.FileUtil;
import com.util.LocalInformation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;

import static com.util.PermissionUtil.isExperimentRead;
import static com.util.PermissionUtil.isExperimentWrite;

/**
 * 映射实验部分
 */
@Controller
@RequestMapping(value = "/experiment_part",produces = "text/html;charset=UTF-8")
public class ExperimentPartController {
    //experiment-input
    @RequestMapping(value = "/data_input_experiment",produces = "text/html;charset=UTF-8")
    public ModelAndView data_input_experiment(HttpServletRequest request){
        ModelAndView modelAndView = new ModelAndView();

        String user_cookie_value = CookieUtil.getUserCookie(request).getValue();
        if (user_cookie_value != null && UserMetadata.OnlineUserId.containsKey(user_cookie_value)){
            UserMetadata.OnlineUserOperatorTime.replace(user_cookie_value, LocalInformation.getTimeID());
            if (isExperimentWrite(user_cookie_value.split("wlcniubi")[2])){
                //进入数据导入界面
                int[] time= LocalInformation.getNowDate(new Date());
                modelAndView.addObject("time",time[0]+"-"+time[1]+"-"+time[2]);
                modelAndView.addObject("id",LocalInformation.getTimeID());
                modelAndView.addObject("author",user_cookie_value.split("wlcniubi")[1]);

                modelAndView.setViewName("data-input-experiment");
            }else {
                modelAndView.setViewName("Permission-Denied");
            }
        }else {
            modelAndView.setViewName("login");
        }

        return modelAndView;
    }

    @RequestMapping(value = "/data_save_experiment_EXPERIMENT",produces = "text/html;charset=UTF-8")
    public void data_save_experiment_EXPERIMENT(HttpServletRequest request,
                                                HttpServletResponse response,
                                                @RequestParam(value = "part1")String part1,
                                                @RequestParam(value = "part2")String part2,
                                                @RequestParam(value = "part3")String part3,
                                                @RequestParam(value = "part4")String part4,
                                                @RequestParam("SEM_IMAGE") CommonsMultipartFile sem_image,
                                                @RequestParam("STM_IMAGE") CommonsMultipartFile stm_image) throws Exception{
        ArrayList<CommonsMultipartFile> files = new ArrayList<CommonsMultipartFile>(){
            {
                add(sem_image);
                add(stm_image);
            }
        };
        int[] time= LocalInformation.getNowDate(new Date());
        String file_path = request.getSession().getServletContext().getRealPath("/")+"/file_data/experiment_part/EXPERIMENT/"+time[0] + "_"+time[1]+"_"+time[2]+"/"+part1.split("wlcniubi")[0]+"_";
        String[] file_names = new String[2];

        for (int i = 0;i < 2;i++){
            if (!files.get(i).getOriginalFilename().equals("")){
                file_names[i] = files.get(i).getOriginalFilename();
                if (FileUtil.createFile(file_path + files.get(i).getOriginalFilename())){
                    File file = new File(file_path + files.get(i).getOriginalFilename());
                    files.get(i).transferTo(file);
                }
            }else {
                file_names[i] = "null";
            }
        }
        String isSuccess = ExperimentOperator.saveExperimentForm(part1,part2,part3,part4,file_names)?"success":"false";

        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setCharacterEncoding("UTF-8");
        PrintWriter out= null;
        out = response.getWriter();
        out.print(isSuccess);
        out.flush();
        out.close();
    }

    @RequestMapping(value = "/experiment_material_acquisition",produces = "text/html;charset=UTF-8")
    public void experiment_material_acquisition(HttpServletResponse response) throws Exception{
        String json = ExperimentOperator.getExperimentMaterial();

        response.setContentType("application/json");
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setCharacterEncoding("UTF-8");
        PrintWriter out= null;
        out = response.getWriter();
        out.print(json);
        out.flush();
        out.close();
    }

    @RequestMapping(value = "/experiment_material_import",produces = "text/html;charset=UTF-8")
    public void experiment_material_import( @RequestParam(value = "tableId")String tableId, @RequestParam(value = "index")String index,HttpServletResponse response) throws Exception{
        String rowContent = ExperimentOperator.getExperimentMaterialContent(tableId,index);

        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setCharacterEncoding("UTF-8");
        PrintWriter out= null;
        out = response.getWriter();
        out.print(rowContent);
        out.flush();
        out.close();
    }

    //experiment-search
    @RequestMapping(value = "/data_search_experiment",produces = "text/html;charset=UTF-8")
    public ModelAndView data_search_experiment(HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView();
        String user_cookie_value = CookieUtil.getUserCookie(request).getValue();
        if(user_cookie_value != null && UserMetadata.OnlineUserOperatorTime.containsKey(user_cookie_value)) {
            UserMetadata.OnlineUserOperatorTime.replace(user_cookie_value, LocalInformation.getTimeID());
            if(isExperimentRead(user_cookie_value.split("wlcniubi")[2])) {
                modelAndView.setViewName("data-search-experiment");
            }
            else {
                modelAndView.setViewName("Permission-Denied");
            }
        }
        else {
            modelAndView.setViewName("login");
        }
        return modelAndView;
    }


    @RequestMapping(value = "/keyword_search_experiment", produces = "text/html;charset=UTF-8")
    public void keyword_search_experiment(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String user_cookie_value = CookieUtil.getUserCookie(request).getValue();
        UserMetadata.OnlineUserOperatorTime.replace(user_cookie_value, LocalInformation.getTimeID());
        String projectPath = request.getSession().getServletContext().getRealPath("/");

        response.setContentType("text/html;charset=utf-8");
        response.setHeader("Cache-Control","no-cache");
        response.setHeader("Pragma","No-cache");
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();
        out.println(ExperimentOperator.setSearchResult(user_cookie_value, projectPath, request.getParameter("base"), request.getParameter("keyword")));
        out.flush();
        out.close();
    }

    @RequestMapping(value = "/generate_experiment_select_result", produces = "text/html;charset=UTF-8")
    public ModelAndView generate_experiment_select_result(@RequestParam(value = "experiment_select_result")String select_data_id ,HttpServletRequest request) throws IOException {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("template-searchTable");
        String user_cookie_value = CookieUtil.getUserCookie(request).getValue();
        UserMetadata.OnlineUserOperatorTime.replace(user_cookie_value, LocalInformation.getTimeID());
        String projectPath = request.getSession().getServletContext().getRealPath("/");

        modelAndView.addObject("table_data",ExperimentOperator.getSearchResult(user_cookie_value, projectPath, select_data_id));
        modelAndView.addObject("table_title",StringUtils.join(ExperimentDao.getTitle().toArray(),"wlcniubi"));
        modelAndView.addObject("data_type", "Experiment");
        return modelAndView;
    }

    /**
     *  实验Excel表单上传
     * @param files
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping("/upload_file")
    public void save_excel_bone_tumor(@RequestParam(value = "excel_files[]", required = false) CommonsMultipartFile[] files, HttpServletRequest request, HttpServletResponse response) throws IOException {
        String user_cookie_value = CookieUtil.getUserCookie(request).getValue();
        String userId = user_cookie_value.split("wlcniubi")[1];

        String error_file = "";
        int error_flag = 0;       // 0-成功 1-后缀错误 2-格式错误

        int[] time= LocalInformation.getNowDate(new Date());
        String date_info = time[0] + "-" + time[1] + "-" + time[2];

        int files_size = files.length;      //判断是否上传
        String[] path_list = new String[files_size];
        String[] timeId_list = new String[files_size];

        for(int i = 0; i < files_size; i++) {
            timeId_list[i] = LocalInformation.getTimeID_bias(i);
            path_list[i] =  request.getSession().getServletContext().getRealPath("/")+"/temp_data/"+userId+"/"+timeId_list[i]+'_';
        }
        for(MultipartFile file :files) {
            String file_name = file.getOriginalFilename();
            if(!file_name.endsWith("xlsx")) {
                System.out.println(file_name);
                error_flag = 1;
                break;
            }
            //上传存储
            FileUtil.data_upload(path_list[files_size - 1], file_name, file);
            //解析excel
            if(!ExperimentOperator.Analysis_experiment_table(timeId_list[files_size - 1], path_list[files_size - 1], file_name, userId, date_info)) {
                error_file = file_name;
                error_flag = 2;
                break;
            };
            files_size--;
        }
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setCharacterEncoding("UTF-8");
        PrintWriter out= null;
        out = response.getWriter();
        if(files_size == 0 && error_flag == 0) {
            out.print("success");
        } else if(files_size != 0 && error_flag == 1) {
            out.print("suffix error");
        } else if(files_size != 0 && error_flag == 2) {
            out.print(error_file);
        }
        out.flush();
        out.close();
    }


}
